package com.rivues.module.manage.web.handler.system;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.rivues.core.RivuDataContext;
import com.rivues.module.platform.web.bean.HelpDetail;
import com.rivues.module.platform.web.bean.HelpGroup;
import com.rivues.module.platform.web.handler.Handler;
import com.rivues.module.platform.web.handler.ResponseData;
import com.rivues.module.platform.web.interceptor.LogIntercreptorHandler;
import com.rivues.module.platform.web.model.ConfigureParam;
import com.rivues.module.platform.web.model.SearchResultTemplet;
import com.rivues.module.platform.web.model.TypeCategory;
import com.rivues.util.RivuTools;
import com.rivues.util.service.cache.CacheHelper;

@Controller
@RequestMapping("/{orgi}/manage/system")
public class SystemController extends Handler {
	private final Logger log = LoggerFactory
			.getLogger(LogIntercreptorHandler.class);

	/**
	 * 
	 * @param request
	 * @param orgi
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/index", name = "index", type = "manage", subtype = "system")
	public ModelAndView index(HttpServletRequest request,
			@PathVariable String orgi) throws Exception {
		// return
		// request(super.createManageTempletResponse("/pages/manage/system/index")
		// , orgi) ;
		ResponseData response = new ResponseData(
				"redirect:/{orgi}/manage/system/sys/servicesetting.html");
		return super.request(response, orgi);
	}
	
	/**
	 * 
	 * @param request
	 * @param orgi
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/export", name = "export", type = "manage", subtype = "system")
	public void export(HttpServletRequest request,HttpServletResponse response ,
			@PathVariable String orgi) throws Exception {
		// return
		// request(super.createManageTempletResponse("/pages/manage/system/index")
		// , orgi) ;
		List exportList = new ArrayList();
		/**
		 * 导出配置表
		 */
		List configParamList =  super.getService().findAllByIObjectCType(ConfigureParam.class) ;
		/**
		 * 导出模板表
		 */
		List templetList =  super.getService().findAllByIObjectCType(SearchResultTemplet.class) ;
		
		/**
		 * 导出分类表
		 */
		List typecategoryList =  super.getService().findAllByIObjectCType(TypeCategory.class) ;
		/**
		 * 数据放入List等待序列化
		 */
		exportList.addAll(templetList) ;
		exportList.addAll(configParamList) ;
		exportList.addAll(typecategoryList) ;
		/**
		 * 当前操作用户同时被导入，通常使用 系统管理员来执行此操作
		 */
		exportList.add(super.getUser(request)) ;
		
		
		/**
		 * 导出数据准备完毕，序列化输出到文件
		 */
		RivuTools.toBytes(exportList) ;
		response.setContentType("charset=UTF-8;application/octet-stream");   
		response.addHeader("Content-Disposition","attachment;filename=\"R3_EXPORT_"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"\".data");  
		response.getOutputStream().write(RivuTools.toBytes(exportList) ) ;
		return ;
	}	

	/**
	 * 
	 * @param request
	 * @param orgi
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/templatelist/{type}/{catagoryid}", name = "templatelist", type = "manage", subtype = "system")
	public ModelAndView templatelist(HttpServletRequest request,
			@PathVariable String orgi, @PathVariable String type,@PathVariable String catagoryid,@Valid String ex)
			throws Exception {
		ModelAndView view = request(
				super.createManageTempletResponse("/pages/manage/system/reportemplatelist"),
				orgi);
		if(ex!=null){
			view.addObject("ex", ex);
		}
		DetachedCriteria criteria = DetachedCriteria.forClass(SearchResultTemplet.class)
				.addOrder(Order.asc("createtime"))
				// .add(Restrictions.eq("orgi", orgi)) //不区分租户
				.add(Restrictions.eq("templettype", type));
		if(catagoryid!=null&&!"0".equals(catagoryid)){
			criteria.add(Restrictions.eq("typeid", catagoryid));
		}
		
		view.addObject("templetList",super.getService().findAllByCriteria(criteria));
		view.addObject("catagoryid",catagoryid);
		view.addObject(
				"catagoryList",
				super.getService().findAllByCriteria(
						DetachedCriteria.forClass(TypeCategory.class)
								.addOrder(Order.asc("createtime"))
								// .add(Restrictions.eq("orgi", orgi)) //不区分租户
								.add(Restrictions.eq("ctype", type))));
		view.addObject("type", type);
		return view;
	}
	
	@RequestMapping(value = "/{type}/catagoryadd", name = "catagoryadd", type = "manage", subtype = "system")
	public ModelAndView catagoryadd(HttpServletRequest request,@PathVariable String orgi,@PathVariable String type) throws Exception {
		ResponseData response = new ResponseData("/pages/manage/system/catagoryadd");
		ModelAndView view = request(response, orgi);
		view.addObject("type",type);
		/**
		 * 更新缓存
		 */
		RivuDataContext.initR3ContextData() ;
		return view;
	}
	@RequestMapping(value = "/{type}/catagoryedit/{catagoryid}", name = "catagoryedit", type = "manage", subtype = "system")
	public ModelAndView catagoryedit(HttpServletRequest request,@PathVariable String orgi,@PathVariable String type,@PathVariable String catagoryid) throws Exception {
		ResponseData response = new ResponseData("/pages/manage/system/catagoryedit");
		ModelAndView view = request(response, orgi);
		view.addObject("catagory",super.getService().getIObjectByPK(TypeCategory.class, catagoryid));
		view.addObject("type",type);
		return view;
	}
	@RequestMapping(value = "/{type}/catagoryedito", name = "catagoryedito", type = "manage", subtype = "system")
	public ModelAndView catagoryedito(HttpServletRequest request,@PathVariable String orgi,@PathVariable String type,@Valid TypeCategory catagory) throws Exception {
		int count = super.getService().getCountByCriteria(DetachedCriteria.forClass(TypeCategory.class).add(Restrictions.eq("name", catagory.getName())));
		ResponseData response = new ResponseData(new StringBuffer().append("redirect:/{orgi}/manage/system/templatelist/{type}/").append(catagory.getId()).append(".html?msgcode=S_MANAGE_10020002").toString());
		TypeCategory cat = (TypeCategory)super.getService().getIObjectByPK(TypeCategory.class, catagory.getId());
		if(count>0&&!cat.getName().equals(catagory.getName())){
			response.setPage(new StringBuffer().append("redirect:/{orgi}/manage/system/templatelist/{type}/").append(catagory.getId()).append(".html?msgcode=E_MANAGE_10020002").toString());
		}else{
			cat.setName(catagory.getName());
			cat.setUpdatetime(new Date());
			cat.setIconstr(catagory.getIconstr());
			cat.setDescription(catagory.getDescription());
			cat.setCode(catagory.getCode());
			super.getService().updateIObject(cat);
		}
		ModelAndView view = request(response, orgi);
		/**
		 * 更新缓存
		 */
		RivuDataContext.initR3ContextData() ;
		return view;
	}
	
	@RequestMapping(value = "/{type}/{catagoryid}/catagorydelo", name = "catagorydelo", type = "manage", subtype = "system")
	public ModelAndView catagorydelo(HttpServletRequest request,@PathVariable String orgi,@PathVariable String type,@PathVariable String catagoryid) throws Exception {
		ResponseData response = new ResponseData("redirect:/{orgi}/manage/system/templatelist/{type}/0.html");
		int count = super.getService().getCountByCriteria(DetachedCriteria.forClass(SearchResultTemplet.class).add(Restrictions.eq("templettype", type)).add(Restrictions.eq("typeid", catagoryid)));
		if(count>0){
			response.setPage("redirect:/{orgi}/manage/system/templatelist/{type}/{catagoryid}.html?msgcode=E_MANAGE_10020003");
		}else{
			TypeCategory cat = new TypeCategory();
			cat.setId(catagoryid);
			super.getService().deleteIObject(cat);
		}
		/**
		 * 更新缓存
		 */
		RivuDataContext.initR3ContextData() ;
		return request(response, orgi);
	}
	@RequestMapping(value = "/{type}/catagoryaddo", name = "catagoryaddo", type = "manage", subtype = "system")
	public ModelAndView catagoryaddo(HttpServletRequest request,@PathVariable String orgi,@PathVariable String type,@Valid TypeCategory catagory) throws Exception {
		ResponseData response = new ResponseData("redirect:/{orgi}/manage/system/templatelist/{type}/0.html?msgcode=E_MANAGE_10020001");
		int count = super.getService().getCountByCriteria(DetachedCriteria.forClass(TypeCategory.class).add(Restrictions.eq("name", catagory.getName())));
		if(count==0){
			catagory.setCtype(type);
			catagory.setOrgi(orgi);
			catagory.setCreater(super.getUser(request).getId());
			catagory.setCreatetime(new Date());
			catagory.setUpdatetime(new Date());
			super.getService().saveIObject(catagory);
			response.setPage(new StringBuffer().append("redirect:/{orgi}/manage/system/templatelist/{type}/").append(catagory.getId()).append(".html?msgcode=S_MANAGE_10020001").toString());
		}
		/**
		 * 更新缓存
		 */
		RivuDataContext.initR3ContextData() ;
		ModelAndView view = request(response, orgi);
		return view;
	}

	@RequestMapping(value = "/templetadd/{type}/{catagoryid}", name = "templetadd", type = "manage", subtype = "system")
	public ModelAndView templetadd(HttpServletRequest request,
			@PathVariable String orgi, @PathVariable String type, @PathVariable String catagoryid)
			throws Exception {
		ModelAndView view = request(
				super.createManageResponse("/pages/manage/system/templetadd"),
				orgi);
		view.addObject("templettype", type);
		view.addObject("catagoryid", catagoryid);
		return view;
	}

	@RequestMapping(value = "/templetadddo/{type}/{catagoryid}", name = "templetadddo", type = "manage", subtype = "system")
	public ModelAndView templetadddo(HttpServletRequest request,
			@PathVariable String orgi, @PathVariable String type,@PathVariable String catagoryid,
			@Valid SearchResultTemplet templet) throws Exception {
		ResponseData response = new ResponseData("redirect:/{orgi}/manage/system/templatelist/{type}/{catagoryid}.html?msgcode=S_MANAGE_10020004");
		int count = super.getService().getCountByCriteria(DetachedCriteria.forClass(SearchResultTemplet.class).add(Restrictions.eq("name", templet.getName())).add(Restrictions.eq("typeid", catagoryid)));
		if(count>0){
			response.setPage("redirect:/{orgi}/manage/system/templatelist/{type}/{catagoryid}.html?msgcode=E_MANAGE_10020004");
		}else{
			templet.setTypeid(catagoryid);
			templet.setCreatetime(new Date());
			templet.setOrgi(orgi);
			super.getService().saveIObject(templet);
			
			CacheHelper.getDistributedDictionaryCacheBean().delete(RivuDataContext.CACHE_TPLRESULT_LIST , orgi);
			
			CacheHelper.getDistributedDictionaryCacheBean().put(templet.getId(), templet, orgi);
		}
		/**
		 * 更新缓存
		 */
		RivuDataContext.initR3ContextData() ;
		return request(response,orgi);
	}

	@RequestMapping(value = "/templetedit/{id}", name = "templetedit", type = "manage", subtype = "system")
	public ModelAndView templetedit(HttpServletRequest request,
			@PathVariable String orgi, @PathVariable String id)
			throws Exception {
		ModelAndView view = request(
				super.createManageResponse("/pages/manage/system/templetedit"),
				orgi);
		view.addObject("templet",
				super.getService()
						.getIObjectByPK(SearchResultTemplet.class, id));
		return view;
	}

	@RequestMapping(value = "/templetcode/{id}", name = "templetcode", type = "manage", subtype = "system")
	public ModelAndView templetcode(HttpServletRequest request,
			@PathVariable String orgi, @PathVariable String id)
			throws Exception {
		ModelAndView view = request(
				super.createManageResponse("/pages/manage/system/templetcode"),
				orgi);
		view.addObject("templet",
				super.getService()
						.getIObjectByPK(SearchResultTemplet.class, id));
		return view;
	}

	@RequestMapping(value = "/templetdel/{id}/{type}/{catagoryid}", name = "templetdel", type = "manage", subtype = "system")
	public ModelAndView templetdel(HttpServletRequest request,
			@PathVariable String orgi, @PathVariable String id,
			@PathVariable String type,@PathVariable String catagoryid) throws Exception {
		SearchResultTemplet templet = new SearchResultTemplet();
		templet.setId(id);
		super.getService().deleteIObject(templet);
		CacheHelper.getDistributedDictionaryCacheBean().delete(templet.getId(), orgi);
		CacheHelper.getDistributedDictionaryCacheBean().delete(RivuDataContext.CACHE_TPLRESULT_LIST , orgi);
		/**
		 * 更新缓存
		 */
		RivuDataContext.initR3ContextData() ;
		return super.request(new ResponseData(
				"redirect:/{orgi}/manage/system/templatelist/{type}/{catagoryid}.html?msgcode=S_MANAGE_10020007"),
				orgi);
	}

	@RequestMapping(value = "/templeteditdo/{type}", name = "templeteditdo", type = "manage", subtype = "system")
	public ModelAndView templeteditdo(HttpServletRequest request,
			@PathVariable String orgi, @PathVariable String type,
			@Valid SearchResultTemplet templet) throws Exception {
		SearchResultTemplet tpl = (SearchResultTemplet) super.getService()
				.getIObjectByPK(SearchResultTemplet.class, templet.getId());
		ResponseData response = new ResponseData(new StringBuffer().append("redirect:/{orgi}/manage/system/templatelist/{type}/").append(tpl.getTypeid()).append(".html?msgcode=S_MANAGE_10020005").toString());
		int count = super.getService().getCountByCriteria(DetachedCriteria.forClass(SearchResultTemplet.class).add(Restrictions.eq("name", templet.getName())).add(Restrictions.eq("typeid", tpl.getTypeid())));
		if(count>0&&!tpl.getName().equals(templet.getName())){
			response.setPage(new StringBuffer().append("redirect:/{orgi}/manage/system/templatelist/{type}/").append(tpl.getTypeid()).append(".html?msgcode=E_MANAGE_10020005").toString());
		}else{
			tpl.setName(templet.getName());
			tpl.setIconstr(templet.getIconstr());
			tpl.setDescription(templet.getDescription());
			tpl.setCode(templet.getCode()) ;
			super.getService().updateIObject(tpl);
			CacheHelper.getDistributedDictionaryCacheBean().update(tpl.getId(), orgi,tpl);
			CacheHelper.getDistributedDictionaryCacheBean().delete(RivuDataContext.CACHE_TPLRESULT_LIST , orgi);
		}
		/**
		 * 更新缓存
		 */
		RivuDataContext.initR3ContextData() ;
		return request(response,orgi);
	}

	@RequestMapping(value = "/templetcodedo/{type}", name = "templeteditdo", type = "manage", subtype = "system")
	public ModelAndView templetcodedo(HttpServletRequest request,
			@PathVariable String orgi, @PathVariable String type,
			@Valid SearchResultTemplet templet) throws Exception {
		SearchResultTemplet tpl = (SearchResultTemplet) super.getService()
				.getIObjectByPK(SearchResultTemplet.class, templet.getId());
		tpl.setTemplettext(templet.getTemplettext());
		super.getService().updateIObject(tpl);
		CacheHelper.getDistributedDictionaryCacheBean().update(tpl.getId(), orgi,tpl);
		CacheHelper.getDistributedDictionaryCacheBean().delete(RivuDataContext.CACHE_TPLRESULT_LIST , orgi);
		/**
		 * 更新缓存
		 */
		RivuDataContext.initR3ContextData() ;
		return super.request(new ResponseData(new StringBuffer().append("redirect:/{orgi}/manage/system/templatelist/{type}/").append(tpl.getTypeid()).append(".html?msgcode=S_MANAGE_10020006").toString()),orgi);
	}

}